import { defineStore } from 'pinia';
import { getToken, setToken, getUserInfo, setUserInfo, clearAuthInfo } from '@/utils/auth';
import { login, userInfo, logout } from '@/api/user';

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userInfo: getUserInfo()
  }),
  actions: {
    login(formData) {
      return new Promise((resolve, reject) => {
        login(formData).then(res => {
          const { token, tokenExpiredTime } = res.data;
          
          this.token = token;
          if (tokenExpiredTime) {
            const expireDate = new Date(tokenExpiredTime.replace(' ', 'T'));

            if (!isNaN(expireDate.getTime())) {
              const now = new Date();
              const timeDiff = expireDate.getTime() - now.getTime();
              const expireDays = timeDiff / (1000 * 60 * 60 * 24);
              setToken(token, Math.max(1, expireDays));
              setUserInfo(res.data, Math.max(1, expireDays))
            } else {
              setToken(token);
              setUserInfo(res.data)
            }
          } else {
            setToken(token);
            setUserInfo(res.data)
          }
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    getInfo() {
      return new Promise((resolve, reject) => {
        userInfo().then(res => {
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    logout() {
      return new Promise((resolve, reject) => {
        logout(this.userInfo.userId).then(() => {
          resolve()
        }).catch(error => {
          reject(error)
        }).finally(() => {
          clearAuthInfo()
        })
      })
    }
  }
});
